package cn.agiledata.bank.barcodepayment.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.agiledata.bank.account.service.AccountSummary;
import cn.agiledata.bank.barcodepayment.exception.BarCodePayException;
import cn.agiledata.bank.barcodepayment.form.BarCodePayForm;
import cn.agiledata.bank.barcodepayment.logic.BarCode;
import cn.agiledata.bank.barcodepayment.service.BarCodePayService;
import cn.agiledata.bank.barcodepayment.service.BarCodeQueryService;
import cn.agiledata.bank.common.bean.SelectBean;
import cn.agiledata.bank.common.servlet.InitForString;
import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.DateUtil;
import cn.agiledata.bank.common.util.MD5;
import cn.agiledata.bank.common.util.PageBean;
import cn.agiledata.bank.common.util.StringUtil;
import cn.agiledata.bank.common.util.WeatherUtil;
import cn.agiledata.bank.common.util.WebUtil;
import cn.agiledata.bank.hibernateBean.Account;
import cn.agiledata.bank.hibernateBean.BarCodePayDetail;
import cn.agiledata.bank.hibernateBean.BarCodePayType;
import com.vnv.infrastructure.action.IPBBaseAction;
import com.vnv.infrastructure.exception.IPBException;
import com.vnv.infrastructure.logic.IPBAppFactory;

public class BarCodePayAction extends IPBBaseAction {

	public int hasAccessPermission(int level, HttpServletRequest request) throws IPBException {
		return 1;
	}

	public BarCodePayService getBarCodePayService() {
		return (BarCodePayService) IPBAppFactory.getObj("barCodePayService");
	}

	public BarCode getBarCode() {
		return (BarCode) IPBAppFactory.getObj("barCodePayService");
	}

	/**
	 * 转向到公共事业费缴费页面
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws IPBException
	 * @throws Exception
	 */
	public ActionForward toBarCodePay(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IPBException, Exception {
		WebUtil.setSessionString(request, "modual", "barcodepay");
		BarCodePayForm form = (BarCodePayForm) actionForm;
		Long typeId = form.getType();

		if (typeId == null) {
			// 默认项目为自来水费
			typeId = new Long(3);
		}

		List corps = new ArrayList();
		corps = getBarCodePayService().getBarCodePayCorpsByType(typeId);
		request.setAttribute("corps", corps);
		request.setAttribute("type", typeId);

		// 取得缴费类型
		BarCodePayType bcpType = getBarCodePayService().getBarCodePayTypeById(typeId);
		request.setAttribute("typeName", bcpType.getName());

		return mapping.findForward("access");
	}

	public ActionForward payHistorySearch(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IPBException, Exception {
		long accountId = WeatherUtil.getAccountIdFromSession(request);
		BarCodePayForm form = (BarCodePayForm) actionForm;
		form.setAccountId(new Long(accountId));
		PageBean pageBean = getBarCodePayService().getPayHistory(form);
		request.setAttribute("pageBean", pageBean);
		List listId = InitForString.getListId("USER_BARCODEPAY_STATUS");
		List listName = InitForString.getListName("USER_BARCODEPAY_STATUS");
		List status = new ArrayList();
		for (int j = 0; j < listId.size(); j++) {
			SelectBean selectBean = new SelectBean(new Long(listId.get(j).toString()), (String) listName.get(j));
			status.add(selectBean);
		}
		List mobStatus = new ArrayList();
		List mobListId =InitForString.getListId("MOBIL_CHARGE_STATUS");
		List mobListName=InitForString.getListName("MOBIL_CHARGE_STATUS");
		for (int j = 0; j < mobListId.size(); j++) {
			if (!mobListId.get(j).toString().equals(Constant.MOBILE_CHARGE_STATUS_CREATE)) {
				SelectBean bean = new SelectBean(new Long(mobListId.get(j).toString()), (String) mobListName.get(j));
				mobStatus.add(bean);
			}
		}
		request.setAttribute("mobStatus", mobStatus);
		request.setAttribute("status", status);
		return mapping.findForward("list");
	}

	// 提交条型码，如果解析成功，就跳转缴费详细页面
	public ActionForward toBarCodePayDetail(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IPBException, Exception {
		BarCodePayForm form = (BarCodePayForm) actionForm;
		String code = form.getCode();
		BarCodePayDetail detail = getBarCodePayService().getBarCodePayDetailByCode(code);
		if (detail != null) {
			form.setCode(detail.getBarCode());
			form.setCorpCode(detail.getBarCodePayCorp().getCode());
			form.setType(detail.getBarCodePayCorp().getBarCodePayType().getId());
		}
		
		 if (getBarCodePayService().ifFeePayed(form.getCode()))
			throw BarCodePayException.ERROR_FEEPAYED;
		BarCode barCode = getBarCodePayService().getBarCode(form.getCorpCode(),
				form.getCode());

		// 超期判断
		if (getBarCodePayService().ifDataExtended(barCode.getDate()))
			throw BarCodePayException.ERROR_DATAEXTENDED;

		form.setType(form.getType());
		request.setAttribute("typeName", getBarCodePayService().getBarCodePayTypeById(form.getType()).getName());
		request.setAttribute("corpName", getBarCodePayService().getBarCodePayCorpsByCode(form.getCorpCode()).getName());
		form.setDate(DateUtil.date2String(barCode.getDate()));
		request.setAttribute("barCode", barCode);

		// 设置商户接口需要用到的参数
		request.setAttribute("merchantId", Constant.BARCODEPAY_ACCOUNTID);
		request.setAttribute("merchantUrl", WebUtil.getRoot(request) + "/page/barcodepay/barCodePaySuccess.do");
		request.setAttribute("responseMode", "3");

		// 判断是否已经有未完成付款的记录
		BarCodeQueryService bcqs = (BarCodeQueryService) IPBAppFactory.getObj("barCodeQueryService");
		BarCodePayDetail bcpd = bcqs.unLogHistoryDetail(form.getCode());

		String barCodePayFeeNo = null;
		if (bcpd == null) {
			// 没有未付款记录，产生新的订单编号
			barCodePayFeeNo = getBarCodePayService().getBarCodePayFeeNo();
		} else {
			// 存在未付款记录，使用旧订单编号
			barCodePayFeeNo = bcpd.getPayFeeNo();
		}
		

		form.setPayFeeNo(barCodePayFeeNo);
		request.setAttribute("orderId", barCodePayFeeNo);
		request.setAttribute("amount", barCode.getAmount());
		request.setAttribute("currencyType", "CNY");
		request.setAttribute("assuredPay", "false");
		String now = DateUtil.date2String(new Date(), "yyyyMMddHHmmss");
		request.setAttribute("time", now);
		String mac = "merchantId=" + Constant.BARCODEPAY_ACCOUNTID + "&merchantUrl=" + WebUtil.getRoot(request);
		mac += "/page/barcodepay/barCodePaySuccess.do";
		mac += "&responseMode=3";
		mac += "&orderId=" + barCodePayFeeNo + "&currencyType=CNY";
		mac += "&amount=" + barCode.getAmount() + "&assuredPay=false";
		mac += "&time=" + now + "&remark=" + "&merchantKey=";
		mac += Constant.BARCODEPAY_KEY;
		mac = new MD5().getMD5ofStr(mac);
		request.setAttribute("mac", mac);

		return mapping.findForward("access");
	}

	/**
	 * 保存公共事业费缴费记录，并提交付款
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws IPBException
	 * @throws Exception
	 */
	public ActionForward barCodePaySave(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IPBException, Exception {
		BarCodePayForm form = (BarCodePayForm) actionForm;
		Account account = null;
		AccountSummary accountSummary = WeatherUtil.getLoingInfoFromSession(request);
		if (accountSummary != null && accountSummary.getAccount().getAccountType().equals(Constant.ACCOUNT_TYPE_BUYER))
			account = accountSummary.getAccount();
		Date chargeDate = DateUtil.string2Date(form.getDate());
		BarCodePayDetail detail = getBarCodePayService().getNewBarCodePayDetail(form, account, chargeDate);
		getBarCodePayService().saveBarCodePayDetail(detail);

		request.getSession().removeAttribute("barFlag");
		String flag = request.getParameter("flag");
		if (StringUtils.isNotBlank(flag)) request.getSession().setAttribute("barFlag", "barCode");
		return mapping.findForward("access");
	}

	public ActionForward barCodePaySuccess(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IPBException, Exception {
		String flag = (String) request.getSession().getAttribute("barFlag");
		if (StringUtils.isNotBlank(flag)) request.setAttribute("flag", "barCode");
		request.getSession().removeAttribute("barFlag");
		if (Constant.RETURNSUCCESS.equals(request.getParameter("returnCode"))) {
			String orderId = request.getParameter("orderId");
			String transId = request.getParameter("unsTransId");
			BarCodePayDetail detail = null;
			synchronized (this) {
				detail = getBarCodePayService().paySuccess(orderId, transId);
			}
			request.setAttribute("detail", detail);
			// 计算验证签名并返回
			request.setAttribute("mac", getBarCodePayService().generateMac(detail));
			return mapping.findForward("success");
		} else {
			return mapping.findForward("failed");
		}
	}

	public ActionForward printBarCodePayDetail(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IPBException, Exception {

		BarCodePayDetail detail = getBarCodePayService().getBarCodePayDetailByPayFeeNo(request.getParameter("orderId"));
		request.setAttribute("detail", detail);
		// 计算验证签名并返回
		request.setAttribute("mac", getBarCodePayService().generateMac(detail));
		return mapping.findForward("access");

	}

	// 未登录查询
	public ActionForward queryUnLog(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IPBException, Exception {
		BarCodePayForm form = (BarCodePayForm) actionForm;
		String barCode = form.getCode();
		if (barCode == null) {
			return mapping.findForward("access");
		}
		if (!StringUtil.isNumber(barCode)) {
			throw BarCodePayException.ERROR_NOTNUMBER;
		}
		BarCodeQueryService bs = (BarCodeQueryService) IPBAppFactory.getObj("barCodeQueryService");
		BarCodePayDetail dd = bs.unLogHistoryDetail(barCode);
		request.setAttribute("detail", dd);
		request.setAttribute("flag", "1");

		List types = getBarCodePayService().getBarCodePayTypes();
		List corps = new ArrayList();
		if (types != null && types.size() > 0) {
			BarCodePayType firstType = (BarCodePayType) types.get(0);
			corps = getBarCodePayService().getBarCodePayCorpsByType(firstType.getId());
		}
		request.setAttribute("types", types);
		request.setAttribute("corps", corps);

		return mapping.findForward("access");
	}

	// 跳转登录查询
	public ActionForward toQueryLog(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IPBException, Exception {
		BarCodeQueryService bs = (BarCodeQueryService) IPBAppFactory.getObj("barCodeQueryService");
		PageBean list = bs.logHistoryDetail(null);
		request.setAttribute("list", list);
		List type = bs.getPayType();
		request.setAttribute("payType", type);
		return mapping.findForward("access");
	}

	// 登录查询
	public ActionForward queryLog(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IPBException, Exception {
		String submitToken = "";
		submitToken = (String) request.getSession().getAttribute("submitToken");
		BarCodePayForm form = (BarCodePayForm) actionForm;
		BarCodeQueryService bs = (BarCodeQueryService) IPBAppFactory.getObj("barCodeQueryService");

		if (submitToken == null || submitToken == "") {
			PageBean list = bs.logHistoryDetail(null);
			request.setAttribute("list", list);
			submitToken = "1";
			request.getSession().setAttribute("submitToken", submitToken);
		} else {
			String barCode = form.getCode();
			if (barCode != null && barCode != "") {
				if (!StringUtil.isNumber(barCode)) {
					throw BarCodePayException.ERROR_NOTNUMBER;
				}
			}
			if (!StringUtil.isStrEmpty(form.getDate())) {
				Date fd = DateUtil.string2Date(form.getDate(), "yyyy-MM");
				form.setFromDate(fd);
				Date td = DateUtil.addDate(fd, 0, 1, 0);
				form.setToDate(td);
			}
			request.setAttribute("list", bs.logHistoryDetail(form));
		}
		List type = bs.getPayType();
		request.setAttribute("payType", type);

		return mapping.findForward("access");
	}

	public ActionForward toBarCodePayHelp(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws IPBException, Exception {
		return mapping.findForward("success");
	}

}
